class MiniAIChat {
    constructor() {
        this.apiBaseUrl = 'http://localhost:5001';
        this.isConnected = false;
        this.isLoading = false;
        
        this.initializeElements();
        this.bindEvents();
        this.checkApiStatus();
        this.loadModelInfo();
        
    }
    
    initializeElements() {
        // 主要元素
        this.chatMessages = document.getElementById('chatMessages');
        this.messageInput = document.getElementById('messageInput');
        this.sendButton = document.getElementById('sendButton');
        this.loadingOverlay = document.getElementById('loadingOverlay');
        
        // 状态元素
        this.statusIndicator = document.getElementById('statusIndicator');
        this.statusText = document.getElementById('statusText');
        this.modelInfo = document.getElementById('modelInfo');
        this.apiStatus = document.getElementById('apiStatus');
        
        // 控制元素
        this.maxLengthSlider = document.getElementById('maxLength');
        this.temperatureSlider = document.getElementById('temperature');
        this.topKSlider = document.getElementById('topK');
        this.maxLengthValue = document.getElementById('maxLengthValue');
        this.temperatureValue = document.getElementById('temperatureValue');
        this.topKValue = document.getElementById('topKValue');
        
        // 按钮
        this.clearButton = document.getElementById('clearButton');
        this.reloadModelButton = document.getElementById('reloadModelButton');
        this.testConnectionButton = document.getElementById('testConnectionButton');
    }
    
    bindEvents() {
        // 发送消息
        this.sendButton.addEventListener('click', () => this.sendMessage());
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });
        
        // 参数滑块
        this.maxLengthSlider.addEventListener('input', (e) => {
            this.maxLengthValue.textContent = e.target.value;
        });
        
        this.temperatureSlider.addEventListener('input', (e) => {
            this.temperatureValue.textContent = parseFloat(e.target.value).toFixed(1);
        });
        
        this.topKSlider.addEventListener('input', (e) => {
            this.topKValue.textContent = e.target.value;
        });
        
        // 功能按钮
        this.clearButton.addEventListener('click', () => this.clearChat());
        this.reloadModelButton.addEventListener('click', () => this.reloadModel());
        this.testConnectionButton.addEventListener('click', () => this.testConnection());
    }
    
    async checkApiStatus() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/health`);
            const data = await response.json();
            
            if (response.ok) {
                this.updateConnectionStatus(true, '已连接');
                this.updateApiStatus(data);
            } else {
                throw new Error('API响应错误');
            }
        } catch (error) {
            console.error('API状态检查失败:', error);
            this.updateConnectionStatus(false, '连接失败');
            this.updateApiStatus({ error: error.message });
        }
    }
    
    async loadModelInfo() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/model/info`);
            const data = await response.json();
            
            if (response.ok) {
                this.updateModelInfo(data);
            } else {
                throw new Error(data.error || '获取模型信息失败');
            }
        } catch (error) {
            console.error('加载模型信息失败:', error);
            this.updateModelInfo({ error: error.message });
        }
    }
    
    updateConnectionStatus(connected, text) {
        this.isConnected = connected;
        this.statusIndicator.className = `status-indicator ${connected ? 'connected' : ''}`;
        this.statusText.textContent = text;
    }
    
    updateApiStatus(data) {
        if (data.error) {
            this.apiStatus.innerHTML = `<p style="color: #ff4444;">错误: ${data.error}</p>`;
        } else {
            this.apiStatus.innerHTML = `
                <p><strong>状态:</strong> ${data.status}</p>
                <p><strong>模型已加载:</strong> ${data.model_loaded ? '是' : '否'}</p>
                <p><strong>设备:</strong> ${data.device || 'N/A'}</p>
            `;
        }
    }
    
    updateModelInfo(data) {
        if (data.error) {
            this.modelInfo.innerHTML = `<p style="color: #ff4444;">错误: ${data.error}</p>`;
        } else {
            this.modelInfo.innerHTML = `
                <p><strong>模型类型:</strong> ${data.model_type}</p>
                <p><strong>词汇表大小:</strong> ${data.vocab_size?.toLocaleString() || 'N/A'}</p>
                <p><strong>嵌入维度:</strong> ${data.embed_dim}</p>
                <p><strong>隐藏层维度:</strong> ${data.hidden_dim}</p>
                <p><strong>层数:</strong> ${data.num_layers}</p>
                <p><strong>最大序列长度:</strong> ${data.max_seq_len}</p>
                <p><strong>参数总数:</strong> ${data.total_parameters?.toLocaleString() || 'N/A'}</p>
                <p><strong>设备:</strong> ${data.device}</p>
            `;
        }
    }
    
    async sendMessage() {
        const message = this.messageInput.value.trim();
        if (!message || this.isLoading || !this.isConnected) return;
        
        // 添加用户消息到聊天
        this.addMessage(message, 'user');
        this.messageInput.value = '';
        
        // 显示加载状态
        this.setLoading(true);
        
        try {
            const response = await fetch(`${this.apiBaseUrl}/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    max_length: parseInt(this.maxLengthSlider.value),
                    temperature: parseFloat(this.temperatureSlider.value),
                    top_k: parseInt(this.topKSlider.value)
                })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.addMessage(data.response || '抱歉，我没有生成回复。', 'ai');
            } else {
                throw new Error(data.error || '请求失败');
            }
        } catch (error) {
            console.error('发送消息失败:', error);
            this.addMessage(`错误: ${error.message}`, 'system');
        } finally {
            this.setLoading(false);
        }
    }
    
    addMessage(content, type) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}-message`;
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        
        if (type === 'system') {
            messageContent.innerHTML = `<p style="color: #ff4444;">${content}</p>`;
        } else {
            messageContent.textContent = content;
        }
        
        messageDiv.appendChild(messageContent);
        this.chatMessages.appendChild(messageDiv);
        
        // 滚动到底部
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }
    
    setLoading(loading) {
        this.isLoading = loading;
        this.loadingOverlay.className = `loading-overlay ${loading ? 'active' : ''}`;
        this.sendButton.disabled = loading;
        this.messageInput.disabled = loading;
    }
    
    clearChat() {
        // 保留系统欢迎消息
        const systemMessage = this.chatMessages.querySelector('.system-message');
        this.chatMessages.innerHTML = '';
        if (systemMessage) {
            this.chatMessages.appendChild(systemMessage);
        }
    }
    
    async reloadModel() {
        try {
            this.setLoading(true);
            const response = await fetch(`${this.apiBaseUrl}/model/reload`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.addMessage('模型重新加载成功！', 'system');
                await this.loadModelInfo();
                await this.checkApiStatus();
            } else {
                throw new Error(data.error || '模型重新加载失败');
            }
        } catch (error) {
            console.error('重载模型失败:', error);
            this.addMessage(`重载模型失败: ${error.message}`, 'system');
        } finally {
            this.setLoading(false);
        }
    }
    
    async testConnection() {
        this.addMessage('正在测试连接...', 'system');
        await this.checkApiStatus();
        
        if (this.isConnected) {
            this.addMessage('连接测试成功！', 'system');
        } else {
            this.addMessage('连接测试失败，请检查API服务器是否正常运行。', 'system');
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.miniAIChat = new MiniAIChat();
    
    // 定期检查连接状态
    setInterval(() => {
        if (window.miniAIChat) {
            window.miniAIChat.checkApiStatus();
        }
    }, 30000); // 每30秒检查一次
    
    console.log('MiniAI 对话系统已初始化');
    console.log('API地址:', window.miniAIChat.apiBaseUrl);
});